# -*- coding: utf-8 -*-
class ArticlesController < ApplicationController
  before_filter :set_author
  before_filter :set_article,
                :only => [ :show, :edit, :update, :destroy ]
  before_filter :must_belongs_to_current_user,
                :only => [ :edit, :update, :destroy ]

# Post ====================
  def new
    @article = Article.new
  end

  def create
    @article = Article.new(params[:article])
    @current_user.articles << @article

    if @article.save
      redirect_to(user_article_path(@current_user.id, @article.id), :notice => 'Article was successfully created.')
    else
      render :action => "new"
    end
  end

# Show ====================
  def index
    @articles = @author.articles

    respond_to do |format|
      format.html
      format.xml { render :xml => @articles }
    end
  end

  def show
    @article.visited += 1
    @article.save

    respond_to do |format|
      format.html { render 'articles/show' }
      format.xml  { render :xml => @article }
      format.js
    end
  end

# Edit ====================
  def edit
  end

  def update
    if @article.update_attributes(params[:article])
      redirect_to(user_article_path(@current_user, @article), :notice => 'Article was successfully updated.')
    else
      render :action => "edit"
    end
  end

  def destroy
    @article.destroy
    redirect_to user_articles_url
  end


private
  def set_author
    @author = User.find(params[:user_id])
  end

  def set_article
    @article = Article.find(params[:id])
  end

  def must_belongs_to_current_user
    redirect_to_login unless @article.belongs_to? @current_user
  end

end
